<template>
  <div>
    <!-- <img :src="aaa" alt="" /> -->
    <n-card :bordered="false" class="fromCard">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        :Toption="userStatus"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :row-key="(row) => row.id"
        ref="actionRef"
        :request="loadDataTable"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addInfo" :disabled="!authority.includes('user_add')">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建
          </n-button>
        </template>
      </BasicTable>
    </n-card>
    <!-- 添加用户 -->
    <n-modal :show="addModal" style="margin-top: 200px">
      <n-card style="width: 1000px" title="新增用户" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="addUser"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="登录名称" path="loginName">
                <n-input
                  placeholder="请输入登录名称"
                  v-model:value="addUser.loginName"
                  maxlength="20"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="登录全名" path="fullName">
                <n-input placeholder="请输入全名" v-model:value="addUser.fullName" maxlength="20" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="所属机构" path="orgCode">
                <n-input
                  placeholder="请输入所属机构"
                  v-model:value="addUser.orgCode"
                  maxlength="20"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="状态" path="status">
                <n-select v-model:value="addUser.status" :options="userOptions" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="邮箱" path="email">
                <n-input placeholder="请输入邮箱" v-model:value="addUser.email" maxlength="300" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="手机号码" path="tel">
                <n-input
                  placeholder="请输入手机号码"
                  v-model:value="addUser.tel"
                  maxlength="20"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="addFrom">确定</n-button>
            <n-button @click="() => (addModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 查看 -->
    <n-modal :show="viewModal" style="margin-top: 200px">
      <n-card style="width: 1000px" title="用户详情" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="登录名称">
                <n-input disabled v-model:value="userInfodata.loginName" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="登录全名">
                <n-input disabled v-model:value="userInfodata.fullName" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="状态">
                <n-input disabled v-model:value="userInfodata.status" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="手机号">
                <n-input disabled v-model:value="userInfodata.tel" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="邮箱">
                <n-input disabled v-model:value="userInfodata.email" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <!-- <n-gi span="1">
              <n-form-item label="性别">
                <n-radio :checked="viewSex === '男'" value="男" readonly> 男 </n-radio>
                <n-radio :checked="viewSex === '女'" value="女" readonly> 女 </n-radio>
              </n-form-item>
            </n-gi> -->
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              @click="() => (viewModal = false)"
              style="background-color: #2d8cf0; color: #fff"
              >确认</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 编辑 -->
    <n-modal :show="editModal" style="margin-top: 200px">
      <n-card style="width: 1000px" title="编辑用户" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="用户id">
                <n-input disabled v-model:value="updataUser.userId" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="登录名">
                <n-input v-model:value="updataUser.loginName" maxlength="20"  disabled />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="登录全名">
                <n-input  v-model:value="updataUser.fullName" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="机构代码">
                <n-input v-model:value="updataUser.orgCode" maxlength="20" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="手机号">
                <n-input  v-model:value="updataUser.tel" maxlength="20" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="邮箱">
                <n-input v-model:value="updataUser.email" maxlength="300" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="状态">
                <n-select
                  placeholder="请选择角色状态"
                  :options="userOptions"
                  v-model:value="updataUser.status"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              type="info"
              :loading="formBtnLoading"
              @click="editFrom"
              style="background-color: #2d8cf0; color: #fff"
              >确定</n-button
            >
            <n-button @click="() => (editModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 分配角色 -->
    <n-modal :show="userRoleModal" style="margin-top: 200px">
      <n-card style="width: 500px" title="用户分配角色" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="userRoleFrom"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-form-item label="" path="userRolee">
            <n-checkbox-group v-if="userRoleModal">
              <n-space item-style="display: flex;" v-for="(item, key) of userList" :key="item.code">
                <n-switch v-model:value="item.isHasRole" @update:value="userSwitch(item, key)" />{{
                  item.name
                }}
              </n-space>
            </n-checkbox-group>
          </n-form-item>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              type="info"
              :loading="formBtnLoading"
              @click="userRoleConfirm"
              :disabled="!authority.includes('userRole_add')"
              >确定</n-button
            >
            <n-button @click="() => (userRoleModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, reactive, onMounted, computed, h } from 'vue';
import { useMessage } from 'naive-ui';
import { DownOutlined, AlignLeftOutlined, SearchOutlined, FormOutlined } from '@vicons/antd';
import { getMenuList } from '@/api/system/menu';
import { getTreeItem } from '@/utils';
import { BasicTable, TableAction } from '@/components/Table';
import { getTableList } from '@/api/table/list';
import { columns } from './cloumns';
import { PlusOutlined } from '@vicons/antd';
import { getUserList } from '@/api/user/list';
import { setList } from '@/api/user/setList';
import { getList } from '@/api/user/getList';
import { addUserInfo } from '@/api/user/add';
import { updataUserInfo } from '@/api/user/updata';
import { viewUserInfo } from '@/api/user/view';
import { BasicForm, useForm } from '@/components/Formdre/index';
import { createStorage } from '@/utils/Storage';
import formatDate from '@/utils/timestamp';
import { log } from 'console';

const Storage = createStorage({ storage: localStorage });

let authorityJson = Storage.get('OPERATORLIST');
const authority = JSON.parse(authorityJson);

// 表单查询按钮
function handleSubmit(values: Recordable) {
  reloadTable();
}

// 表单重置按钮
function handleReset(values: Recordable) {
  userListparm.value.userId = '';
  reloadTable();
}

const belongSystemOptions = [
  {
    label: '前台',
    value: 0,
  },
  {
    label: '后台',
    value: 1,
  },
];
const userOptions = [
  {
    value: 0,
    label: '正常',
  },
  {
    value: 1,
    label: '锁定',
  },
];

// 获取全体用户列表
var loadDataTable = async (res) => {
  console.log(res);
  userListparm.value.pageNum = res.page;
  userListparm.value.pageSize = res.pageSize;
  let data = await getUserList(userListparm.value);
  data.data.body.list.forEach((val) => {
    if (val.status == '0') {
      val.status = '正常';
    } else {
      val.status = '锁定';
    }
  });
  let datas = {
    list: data.data.body.list,
    page: res.page,
    pageSize: res.pageSize,
    pageCount: Math.ceil(data.data.body.total / res.pageSize),
  };
  console.log(datas);
  return datas;
};

const userListparm = ref({
  userId: '',
  pageNum: 1,
  pageSize: 10,
});

// 表单输入框和表单验证
const schemas = [
  {
    field: 'name',
    component: 'NInput',
    label: '用户ID：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入角色ID',
      onInput: (e: any) => {
        console.log(e);
        userListparm.value.userId = e;
      },
    },
  },
];

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});
console.log(authority);

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '编辑',
          text: true,
          color: '#2d8cf0',
          onClick: editUserInfo.bind(null, record),
          ifShow: () => {
            return authority.includes('user_update');
            // :disabled='!authority.includes("org_view")'
          },
        },
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: viewInfo.bind(null, record),
          ifShow: () => {
            return authority.includes('user_view');
          },
        },
        {
          label: '修改角色',
          text: true,
          color: '#2d8cf0',
          onClick: userRole.bind(null, record),
          ifShow: () => {
            return authority.includes('userRole_view');
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

// 表格刷新
function reloadTable() {
  actionRef.value.reload();
}
function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

// 模态框控制和数据
const editModal = ref(false);
const viewUsertype = ref('超级管理员');
const merchantState = ref('正常');
const viewSex = ref('女');
const delModal = ref(false);
const viewModal = ref(false);
const resetPassword = ref(false);
const addModal = ref(false);
const userRoleModal = ref(false);

// 表单和列表
const actionRef = ref();
const formRef = ref();
const createDrawerRef = ref();
const message = useMessage();

// 分配角色
const userRoleFrom = ref({
  userId: '',
  roleCode: [],
});
const userList = ref({});

const setListParm = ref({
  userId: '01',
  roleList: '',
});

// 修改角色
function userRole(record: Recordable) {
  userRoleFrom.value.userId = record.userId;
  getList(userRoleFrom.value).then((val) => {
    console.log(val);
    userList.value = val.data.body;
    userRoleModal.value = true;
    console.log(userList.value);
  });
  console.log(record);
}

const roleCode = ref([]);

const userSwitch = (val, key) => {
  console.log(userList.value);
  userRoleFrom.value.roleCode = userList.value;
  console.log(userList.value);
  userList.value.forEach((val) => {
    if (val.isHasRole) {
      console.log(val.code);
    }
  });
};

// 确认修改
function userRoleConfirm() {
  userRoleModal.value = false;
  userList.value.forEach((val) => {
    if (val.isHasRole) {
      roleCode.value.push(val.code);
    }
  });
  setTimeout(() => {
    userRoleFrom.value.roleCode = roleCode.value;
    setList(userRoleFrom.value).then((val) => {
      console.log(val);
      roleCode.value = [];
    });
  }, 1);
}

// 添加
function addInfo(record: Recordable) {
  console.log('点击了添加', record);
  addModal.value = true;
  addUser.value.email = '';
  addUser.value.loginName = '';
  addUser.value.fullName = '';
  addUser.value.status = '';
  addUser.value.tel = '';
}
let custNoValue = Storage.get('custNo');

// 添加用户模态框表单
const addUser = ref({
  loginName: '',
  fullName: '',
  status: '',
  email: '',
  tel: '',
  custNo: custNoValue,
});

// 添加用户表单验证规则
const rules = {
  loginName: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入登录名称');
      } else {
        return true;
      }
    },
    message: '请输入登录名称',
    trigger: 'blur',
  },
  fullName: {
    required: false,
    message: '请输入全名',
    trigger: 'blur',
  },
  orgCode: {
    required: true,
    message: '请输入机构代码',
    trigger: 'blur',
  },
  email: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入邮箱');
      } else if (!/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(value)) {
        return new Error('请输入正确邮箱');
      } else {
        return true;
      }
    },
    trigger: 'blur',
  },
  sex: {
    required: true,
    trigger: 'change',
    message: '请选择性别',
  },
  userType: {
    required: true,
    trigger: 'change',
    message: '请选择用户类型',
  },
  tel: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入手机号');
      } else if (!/^1[3|4|5|7|8][0-9]{9}$/.test(value)) {
        return new Error('请输入正确的手机号码格式');
      } else {
        return true;
      }
    },
    trigger: 'blur',
  },
};

// 添加确认按钮
const addFrom = async (e) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      console.log(addUser.value);
      let data = await addUserInfo(addUser.value).then((res) => {
        message.success('添加成功');
        console.log(res);
      });
      addModal.value = false;
    } else {
      message.error('添加失败');
    }
  });
};

// 编辑模态框数据
const updataUser = ref({
  email: '',
  fullName: '',
  loginName: '',
  tel: '',
  userId: '',
  status: '',
  orgCode: '',
});

// 编辑
async function editUserInfo(record: Recordable) {
  console.log(record);
  updataUser.value.email = record.email;
  updataUser.value.fullName = record.fullName;
  updataUser.value.loginName = record.loginName;
  updataUser.value.tel = record.tel;
  updataUser.value.userId = record.userId;
  updataUser.value.status = record.status;
  editModal.value = true;
}

// 编辑确认按钮
const editFrom = (e) => {
  formRef.value.validate((errors) => {
    if (!errors) {
      console.log(updataUser.value);
      if (updataUser.value.status == '正常') {
        updataUser.value.status = '0';
      }
      if (updataUser.value.status == '锁定') {
        updataUser.value.status = '1';
      }
      updataUserInfo(updataUser.value).then((val) => {
        reloadTable();
      });
      message.success('编辑成功');
      editModal.value = false;
    } else {
      message.error('编辑失败');
    }
  });
};

// 查看
const userInfodata = ref({});
function viewInfo(record: Recordable) {
  console.log(record);

  userInfodata.value.email = record.email;
  userInfodata.value.fullName = record.fullName;
  userInfodata.value.loginName = record.loginName;
  userInfodata.value.tel = record.tel;
  userInfodata.value.userId = record.userId;
  userInfodata.value.status = record.status;
  viewModal.value = true;
}

// 重置密码
function resetInfo(record: Recordable) {
  console.log('点击了重置', record);
  message.info('点击了重置');
  resetPassword.value = true;
}

//确认重置密码
function onconfirmres() {
  message.success('密码重置成功');
  resetPassword.value = false;
}

//取消重置密码
function oncancelres() {
  message.success('未重置');
  resetPassword.value = false;
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
</style>